#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工厂方法模式 (Factory Method Pattern) - Python实现详解

🎯 模式概述：
工厂方法模式定义一个创建对象的接口，让子类决定实例化哪一个类。
Python的动态特性和鸭子类型让工厂模式的实现更加灵活和简洁。

📚 Java vs Python 对比：

Java实现：
public abstract class PaymentFactory {
    public abstract Payment createPayment();
    
    public void processPayment(double amount) {
        Payment payment = createPayment();
        payment.pay(amount);
    }
}

public class CreditCardFactory extends PaymentFactory {
    @Override
    public Payment createPayment() {
        return new CreditCardPayment();
    }
}

Python的优势：
1. 不需要严格的接口定义（鸭子类型）
2. 可以使用函数作为工厂
3. 支持动态类型和反射
4. 装饰器可以简化工厂注册
5. 字典映射比switch语句更灵活

💡 关键理解：
Python的工厂模式更注重实用性，可以根据需要选择类工厂、函数工厂或注册表工厂。
"""

from abc import ABC, abstractmethod
from typing import Dict, Type, Any, Optional, Callable, Protocol
from enum import Enum
import json
import logging
from dataclasses import dataclass
from datetime import datetime


# ==================== 产品接口和具体产品 ====================
# 对应Java的接口和实现类

class Payment(Protocol):
    """
    支付协议 - Python的Protocol比Java接口更灵活
    
    Java等价接口：
    public interface Payment {
        boolean pay(double amount);
        String getPaymentMethod();
        PaymentResult getLastResult();
    }
    
    Python Protocol的优势：
    1. 结构化子类型（structural subtyping）
    2. 不需要显式继承
    3. 支持鸭子类型
    4. 更好的类型检查
    """
    
    def pay(self, amount: float) -> bool:
        """执行支付"""
        ...
    
    def get_payment_method(self) -> str:
        """获取支付方式"""
        ...
    
    def get_last_result(self) -> Dict[str, Any]:
        """获取最后一次支付结果"""
        ...


@dataclass
class PaymentResult:
    """
    支付结果数据类 - 使用@dataclass简化Java的POJO
    
    Java等价类：
    public class PaymentResult {
        private boolean success;
        private String transactionId;
        private String message;
        private double amount;
        private LocalDateTime timestamp;
        
        // 构造函数、getter、setter、equals、hashCode、toString
    }
    
    Python @dataclass的优势：
    1. 自动生成构造函数、__eq__、__repr__等方法
    2. 类型注解支持
    3. 代码更简洁
    4. 支持默认值和工厂函数
    """
    success: bool
    transaction_id: str
    message: str
    amount: float
    timestamp: datetime = None
    
    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = datetime.now()


class CreditCardPayment:
    """
    信用卡支付 - 具体产品实现
    
    Java等价类：
    public class CreditCardPayment implements Payment {
        private String cardNumber;
        private PaymentResult lastResult;
        
        public CreditCardPayment(String cardNumber) {
            this.cardNumber = cardNumber;
        }
        
        @Override
        public boolean pay(double amount) {
            // 支付逻辑
            this.lastResult = new PaymentResult(true, generateId(), "Success", amount);
            return true;
        }
    }
    """
    
    def __init__(self, card_number: str = "**** **** **** 1234"):
        self.card_number = card_number
        self.last_result: Optional[PaymentResult] = None
        print(f"💳 初始化信用卡支付: {card_number}")
    
    def pay(self, amount: float) -> bool:
        """执行信用卡支付"""
        print(f"💳 信用卡支付: ${amount:.2f}")
        
        # 模拟支付处理
        if amount > 0 and amount <= 10000:
            transaction_id = f"CC_{datetime.now().strftime('%Y%m%d%H%M%S')}"
            self.last_result = PaymentResult(
                success=True,
                transaction_id=transaction_id,
                message="信用卡支付成功",
                amount=amount
            )
            print(f"✅ 支付成功，交易ID: {transaction_id}")
            return True
        else:
            self.last_result = PaymentResult(
                success=False,
                transaction_id="",
                message="支付金额无效",
                amount=amount
            )
            print(f"❌ 支付失败: 金额无效")
            return False
    
    def get_payment_method(self) -> str:
        return "Credit Card"
    
    def get_last_result(self) -> Dict[str, Any]:
        if self.last_result:
            return {
                'success': self.last_result.success,
                'transaction_id': self.last_result.transaction_id,
                'message': self.last_result.message,
                'amount': self.last_result.amount,
                'timestamp': self.last_result.timestamp.isoformat()
            }
        return {}


class PayPalPayment:
    """
    PayPal支付 - 另一个具体产品实现
    
    Java等价类：
    public class PayPalPayment implements Payment {
        private String email;
        private PaymentResult lastResult;
        
        public PayPalPayment(String email) {
            this.email = email;
        }
    }
    """
    
    def __init__(self, email: str = "user@example.com"):
        self.email = email
        self.last_result: Optional[PaymentResult] = None
        print(f"🅿️ 初始化PayPal支付: {email}")
    
    def pay(self, amount: float) -> bool:
        """执行PayPal支付"""
        print(f"🅿️ PayPal支付: ${amount:.2f}")
        
        # 模拟PayPal支付处理
        if amount > 0 and amount <= 5000:
            transaction_id = f"PP_{datetime.now().strftime('%Y%m%d%H%M%S')}"
            self.last_result = PaymentResult(
                success=True,
                transaction_id=transaction_id,
                message="PayPal支付成功",
                amount=amount
            )
            print(f"✅ PayPal支付成功，交易ID: {transaction_id}")
            return True
        else:
            self.last_result = PaymentResult(
                success=False,
                transaction_id="",
                message="PayPal支付金额超限",
                amount=amount
            )
            print(f"❌ PayPal支付失败: 金额超限")
            return False
    
    def get_payment_method(self) -> str:
        return "PayPal"
    
    def get_last_result(self) -> Dict[str, Any]:
        if self.last_result:
            return {
                'success': self.last_result.success,
                'transaction_id': self.last_result.transaction_id,
                'message': self.last_result.message,
                'amount': self.last_result.amount,
                'timestamp': self.last_result.timestamp.isoformat()
            }
        return {}


class BankTransferPayment:
    """
    银行转账支付 - 第三个具体产品实现
    """
    
    def __init__(self, account_number: str = "123456789"):
        self.account_number = account_number
        self.last_result: Optional[PaymentResult] = None
        print(f"🏦 初始化银行转账: {account_number}")
    
    def pay(self, amount: float) -> bool:
        """执行银行转账支付"""
        print(f"🏦 银行转账: ${amount:.2f}")
        
        # 模拟银行转账处理（通常有更高的限额）
        if amount > 0 and amount <= 50000:
            transaction_id = f"BT_{datetime.now().strftime('%Y%m%d%H%M%S')}"
            self.last_result = PaymentResult(
                success=True,
                transaction_id=transaction_id,
                message="银行转账成功",
                amount=amount
            )
            print(f"✅ 银行转账成功，交易ID: {transaction_id}")
            return True
        else:
            self.last_result = PaymentResult(
                success=False,
                transaction_id="",
                message="银行转账金额无效",
                amount=amount
            )
            print(f"❌ 银行转账失败: 金额无效")
            return False
    
    def get_payment_method(self) -> str:
        return "Bank Transfer"
    
    def get_last_result(self) -> Dict[str, Any]:
        if self.last_result:
            return {
                'success': self.last_result.success,
                'transaction_id': self.last_result.transaction_id,
                'message': self.last_result.message,
                'amount': self.last_result.amount,
                'timestamp': self.last_result.timestamp.isoformat()
            }
        return {}


# ==================== 方法1: 经典工厂方法模式 ====================
# 最接近Java的实现方式

class PaymentFactory(ABC):
    """
    抽象支付工厂 - 对应Java的抽象工厂类
    
    Java等价抽象类：
    public abstract class PaymentFactory {
        public abstract Payment createPayment(String... params);
        
        public final PaymentResult processPayment(double amount, String... params) {
            Payment payment = createPayment(params);
            boolean success = payment.pay(amount);
            return payment.getLastResult();
        }
    }
    
    Python ABC的优势：
    1. 抽象基类提供接口约束
    2. 可以包含具体方法实现
    3. 支持多重继承
    4. 更灵活的抽象方法定义
    """
    
    @abstractmethod
    def create_payment(self, **kwargs) -> Payment:
        """抽象工厂方法 - 子类必须实现"""
        pass
    
    def process_payment(self, amount: float, **kwargs) -> Dict[str, Any]:
        """
        模板方法 - 定义支付处理流程
        
        这是模板方法模式和工厂方法模式的结合
        Java中需要final关键字防止重写，Python依赖约定
        """
        print(f"\n🔄 开始处理支付: ${amount:.2f}")
        
        # 使用工厂方法创建支付对象
        payment = self.create_payment(**kwargs)
        
        # 执行支付
        success = payment.pay(amount)
        
        # 返回结果
        result = payment.get_last_result()
        print(f"📊 支付结果: {'成功' if success else '失败'}")
        
        return result


class CreditCardFactory(PaymentFactory):
    """
    信用卡支付工厂 - 具体工厂实现
    
    Java等价类：
    public class CreditCardFactory extends PaymentFactory {
        @Override
        public Payment createPayment(String... params) {
            String cardNumber = params.length > 0 ? params[0] : "**** **** **** 1234";
            return new CreditCardPayment(cardNumber);
        }
    }
    """
    
    def create_payment(self, **kwargs) -> Payment:
        """创建信用卡支付对象"""
        card_number = kwargs.get('card_number', '**** **** **** 1234')
        return CreditCardPayment(card_number)


class PayPalFactory(PaymentFactory):
    """
    PayPal支付工厂 - 具体工厂实现
    """
    
    def create_payment(self, **kwargs) -> Payment:
        """创建PayPal支付对象"""
        email = kwargs.get('email', 'user@example.com')
        return PayPalPayment(email)


class BankTransferFactory(PaymentFactory):
    """
    银行转账支付工厂 - 具体工厂实现
    """
    
    def create_payment(self, **kwargs) -> Payment:
        """创建银行转账支付对象"""
        account_number = kwargs.get('account_number', '123456789')
        return BankTransferPayment(account_number)


# ==================== 方法2: 简单工厂（函数式） ====================
# 利用Python的函数特性，比Java更简洁

class PaymentType(Enum):
    """
    支付类型枚举 - 对应Java的enum
    
    Java等价枚举：
    public enum PaymentType {
        CREDIT_CARD("credit_card"),
        PAYPAL("paypal"),
        BANK_TRANSFER("bank_transfer");
        
        private final String value;
        
        PaymentType(String value) {
            this.value = value;
        }
    }
    
    Python枚举的优势：
    1. 更简洁的定义语法
    2. 支持自动值生成
    3. 可以包含方法
    4. 更好的字符串表示
    """
    CREDIT_CARD = "credit_card"
    PAYPAL = "paypal"
    BANK_TRANSFER = "bank_transfer"


def create_payment(payment_type: PaymentType, **kwargs) -> Payment:
    """
    简单工厂函数 - Python特有的函数式工厂
    
    Java等价静态方法：
    public static Payment createPayment(PaymentType type, Map<String, String> params) {
        switch (type) {
            case CREDIT_CARD:
                return new CreditCardPayment(params.get("cardNumber"));
            case PAYPAL:
                return new PayPalPayment(params.get("email"));
            case BANK_TRANSFER:
                return new BankTransferPayment(params.get("accountNumber"));
            default:
                throw new IllegalArgumentException("Unsupported payment type: " + type);
        }
    }
    
    Python函数工厂的优势：
    1. 不需要类包装
    2. 字典映射比switch更灵活
    3. 支持动态参数
    4. 更简洁的实现
    """
    
    # 使用字典映射替代switch语句
    payment_classes = {
        PaymentType.CREDIT_CARD: CreditCardPayment,
        PaymentType.PAYPAL: PayPalPayment,
        PaymentType.BANK_TRANSFER: BankTransferPayment
    }
    
    payment_class = payment_classes.get(payment_type)
    if not payment_class:
        raise ValueError(f"不支持的支付类型: {payment_type}")
    
    # 根据支付类型传递不同的参数
    if payment_type == PaymentType.CREDIT_CARD:
        return payment_class(kwargs.get('card_number', '**** **** **** 1234'))
    elif payment_type == PaymentType.PAYPAL:
        return payment_class(kwargs.get('email', 'user@example.com'))
    elif payment_type == PaymentType.BANK_TRANSFER:
        return payment_class(kwargs.get('account_number', '123456789'))
    
    # 默认无参数构造
    return payment_class()


# ==================== 方法3: 注册表工厂 ====================
# Python特有的动态注册机制

class PaymentRegistry:
    """
    支付方式注册表 - Python特有的动态工厂
    
    Java等价实现需要复杂的反射机制：
    public class PaymentRegistry {
        private static final Map<String, Class<? extends Payment>> registry = new HashMap<>();
        
        public static void register(String name, Class<? extends Payment> clazz) {
            registry.put(name, clazz);
        }
        
        public static Payment create(String name, Object... args) {
            Class<? extends Payment> clazz = registry.get(name);
            if (clazz == null) {
                throw new IllegalArgumentException("Unknown payment type: " + name);
            }
            try {
                return clazz.getDeclaredConstructor(String.class).newInstance(args);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    Python注册表的优势：
    1. 动态类型支持
    2. 不需要复杂的反射
    3. 支持运行时注册
    4. 更灵活的参数传递
    """
    
    _registry: Dict[str, Type[Payment]] = {}
    _factories: Dict[str, Callable] = {}
    
    @classmethod
    def register(cls, name: str, payment_class: Type[Payment], 
                factory_func: Optional[Callable] = None) -> None:
        """
        注册支付方式
        
        Args:
            name: 支付方式名称
            payment_class: 支付类
            factory_func: 可选的工厂函数
        """
        cls._registry[name] = payment_class
        if factory_func:
            cls._factories[name] = factory_func
        print(f"📝 注册支付方式: {name} -> {payment_class.__name__}")
    
    @classmethod
    def create(cls, name: str, **kwargs) -> Payment:
        """
        创建支付对象
        
        Args:
            name: 支付方式名称
            **kwargs: 构造参数
        
        Returns:
            Payment: 支付对象实例
        """
        if name in cls._factories:
            # 使用自定义工厂函数
            return cls._factories[name](**kwargs)
        
        payment_class = cls._registry.get(name)
        if not payment_class:
            raise ValueError(f"未注册的支付方式: {name}")
        
        # 使用默认构造方式
        return payment_class(**kwargs)
    
    @classmethod
    def list_payments(cls) -> list[str]:
        """列出所有注册的支付方式"""
        return list(cls._registry.keys())
    
    @classmethod
    def unregister(cls, name: str) -> bool:
        """注销支付方式"""
        if name in cls._registry:
            del cls._registry[name]
            if name in cls._factories:
                del cls._factories[name]
            print(f"🗑️ 注销支付方式: {name}")
            return True
        return False


# 注册装饰器 - Python特有的优雅注册方式
def register_payment(name: str, factory_func: Optional[Callable] = None):
    """
    支付方式注册装饰器
    
    Java中没有对应的简洁实现，需要手动调用注册方法
    
    使用示例：
    @register_payment("wechat")
    class WeChatPayment:
        pass
    """
    def decorator(payment_class: Type[Payment]):
        PaymentRegistry.register(name, payment_class, factory_func)
        return payment_class
    return decorator


# 使用装饰器注册支付方式
@register_payment("credit_card")
class RegisteredCreditCardPayment(CreditCardPayment):
    """注册版信用卡支付"""
    pass


@register_payment("paypal")
class RegisteredPayPalPayment(PayPalPayment):
    """注册版PayPal支付"""
    pass


# ==================== 方法4: 配置驱动工厂 ====================
# 企业级应用中常见的配置化工厂

class ConfigurablePaymentFactory:
    """
    配置驱动的支付工厂 - 企业级实现
    
    Java等价实现需要Spring框架支持：
    @Configuration
    public class PaymentConfig {
        @Bean
        @ConditionalOnProperty(name = "payment.type", havingValue = "credit_card")
        public Payment creditCardPayment() {
            return new CreditCardPayment();
        }
    }
    
    Python的优势：
    1. 不需要复杂的依赖注入框架
    2. JSON配置更直观
    3. 动态加载和热更新
    4. 更灵活的条件判断
    """
    
    def __init__(self, config_file: Optional[str] = None):
        self.config = self._load_config(config_file)
        self._payment_cache: Dict[str, Payment] = {}
    
    def _load_config(self, config_file: Optional[str]) -> Dict[str, Any]:
        """加载配置文件"""
        if config_file:
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except FileNotFoundError:
                print(f"⚠️ 配置文件未找到: {config_file}，使用默认配置")
        
        # 默认配置
        return {
            "payment_methods": {
                "credit_card": {
                    "class": "CreditCardPayment",
                    "enabled": True,
                    "max_amount": 10000,
                    "default_params": {
                        "card_number": "**** **** **** 1234"
                    }
                },
                "paypal": {
                    "class": "PayPalPayment",
                    "enabled": True,
                    "max_amount": 5000,
                    "default_params": {
                        "email": "user@example.com"
                    }
                },
                "bank_transfer": {
                    "class": "BankTransferPayment",
                    "enabled": False,  # 可以通过配置禁用
                    "max_amount": 50000,
                    "default_params": {
                        "account_number": "123456789"
                    }
                }
            }
        }
    
    def create_payment(self, payment_type: str, **kwargs) -> Payment:
        """
        根据配置创建支付对象
        
        Args:
            payment_type: 支付类型
            **kwargs: 覆盖默认参数
        
        Returns:
            Payment: 支付对象实例
        """
        config = self.config["payment_methods"].get(payment_type)
        if not config:
            raise ValueError(f"未配置的支付方式: {payment_type}")
        
        if not config.get("enabled", True):
            raise ValueError(f"支付方式已禁用: {payment_type}")
        
        # 合并默认参数和传入参数
        params = config.get("default_params", {}).copy()
        params.update(kwargs)
        
        # 根据类名创建实例
        class_name = config["class"]
        payment_classes = {
            "CreditCardPayment": CreditCardPayment,
            "PayPalPayment": PayPalPayment,
            "BankTransferPayment": BankTransferPayment
        }
        
        payment_class = payment_classes.get(class_name)
        if not payment_class:
            raise ValueError(f"未知的支付类: {class_name}")
        
        # 创建并缓存实例（可选的单例模式）
        cache_key = f"{payment_type}_{hash(frozenset(params.items()))}"
        if cache_key not in self._payment_cache:
            if payment_type == "credit_card":
                self._payment_cache[cache_key] = payment_class(params.get('card_number'))
            elif payment_type == "paypal":
                self._payment_cache[cache_key] = payment_class(params.get('email'))
            elif payment_type == "bank_transfer":
                self._payment_cache[cache_key] = payment_class(params.get('account_number'))
        
        return self._payment_cache[cache_key]
    
    def get_max_amount(self, payment_type: str) -> float:
        """获取支付方式的最大金额限制"""
        config = self.config["payment_methods"].get(payment_type)
        return config.get("max_amount", 0) if config else 0
    
    def is_enabled(self, payment_type: str) -> bool:
        """检查支付方式是否启用"""
        config = self.config["payment_methods"].get(payment_type)
        return config.get("enabled", False) if config else False


# ==================== 测试和演示 ====================

def demonstrate_factory_patterns():
    """
    演示各种工厂模式实现
    
    🎯 学习重点：
    1. 理解Python多种工厂实现方式
    2. 对比Java实现的差异和优势
    3. 选择合适的工厂模式
    4. 理解配置驱动和注册表模式
    """
    print("\n" + "="*60)
    print("🏭 工厂方法模式 (Factory Method Pattern) 演示")
    print("="*60)
    
    # 1. 经典工厂方法模式测试
    print("\n1️⃣ 经典工厂方法模式测试")
    print("-" * 40)
    
    # 创建不同的工厂
    credit_factory = CreditCardFactory()
    paypal_factory = PayPalFactory()
    bank_factory = BankTransferFactory()
    
    # 使用工厂处理支付
    result1 = credit_factory.process_payment(100.0, card_number="1234 5678 9012 3456")
    result2 = paypal_factory.process_payment(50.0, email="alice@example.com")
    result3 = bank_factory.process_payment(1000.0, account_number="987654321")
    
    print(f"信用卡支付结果: {result1['success']}")
    print(f"PayPal支付结果: {result2['success']}")
    print(f"银行转账结果: {result3['success']}")
    
    # 2. 简单工厂（函数式）测试
    print("\n2️⃣ 简单工厂（函数式）测试")
    print("-" * 40)
    
    # 使用函数工厂创建支付对象
    payment1 = create_payment(PaymentType.CREDIT_CARD, card_number="9999 8888 7777 6666")
    payment2 = create_payment(PaymentType.PAYPAL, email="bob@example.com")
    payment3 = create_payment(PaymentType.BANK_TRANSFER, account_number="555666777")
    
    # 执行支付
    payment1.pay(200.0)
    payment2.pay(75.0)
    payment3.pay(1500.0)
    
    print(f"支付方式: {payment1.get_payment_method()}, {payment2.get_payment_method()}, {payment3.get_payment_method()}")
    
    # 3. 注册表工厂测试
    print("\n3️⃣ 注册表工厂测试")
    print("-" * 40)
    
    # 手动注册支付方式
    PaymentRegistry.register("bank_transfer", BankTransferPayment)
    
    # 列出所有注册的支付方式
    print(f"已注册的支付方式: {PaymentRegistry.list_payments()}")
    
    # 使用注册表创建支付对象
    payment4 = PaymentRegistry.create("credit_card")
    payment5 = PaymentRegistry.create("paypal", email="charlie@example.com")
    
    payment4.pay(300.0)
    payment5.pay(125.0)
    
    # 4. 配置驱动工厂测试
    print("\n4️⃣ 配置驱动工厂测试")
    print("-" * 40)
    
    config_factory = ConfigurablePaymentFactory()
    
    # 检查支付方式状态
    print(f"信用卡支付启用: {config_factory.is_enabled('credit_card')}")
    print(f"银行转账启用: {config_factory.is_enabled('bank_transfer')}")
    print(f"PayPal最大金额: ${config_factory.get_max_amount('paypal')}")
    
    # 使用配置工厂创建支付
    try:
        payment6 = config_factory.create_payment("credit_card")
        payment7 = config_factory.create_payment("paypal", email="david@example.com")
        
        payment6.pay(400.0)
        payment7.pay(80.0)
        
        # 尝试使用禁用的支付方式
        payment8 = config_factory.create_payment("bank_transfer")
    except ValueError as e:
        print(f"❌ 配置错误: {e}")
    
    # 5. 工厂模式的多态性测试
    print("\n5️⃣ 工厂模式多态性测试")
    print("-" * 40)
    
    def process_payments_polymorphically(factories: list[PaymentFactory], amount: float):
        """
        多态地处理不同工厂的支付
        
        这展示了工厂模式的多态特性，类似Java的多态
        """
        results = []
        for factory in factories:
            result = factory.process_payment(amount)
            results.append(result)
        return results
    
    # 创建工厂列表
    factories = [CreditCardFactory(), PayPalFactory(), BankTransferFactory()]
    
    # 多态处理
    results = process_payments_polymorphically(factories, 250.0)
    
    print("\n📊 多态支付结果:")
    for i, result in enumerate(results):
        print(f"  工厂{i+1}: {'成功' if result.get('success') else '失败'}")
    
    print("\n📚 工厂模式总结")
    print("-" * 40)
    print("✅ 经典工厂方法: 最符合OOP原则，适合复杂场景")
    print("✅ 简单工厂函数: 最简洁，适合简单场景")
    print("✅ 注册表工厂: 最灵活，支持动态注册")
    print("✅ 配置驱动工厂: 最实用，适合企业应用")


def demonstrate_advanced_features():
    """
    演示工厂模式的高级特性
    """
    print("\n" + "="*60)
    print("🚀 工厂模式高级特性演示")
    print("="*60)
    
    # 1. 工厂链模式
    print("\n1️⃣ 工厂链模式")
    print("-" * 30)
    
    class PaymentFactoryChain:
        """
        工厂链 - 按优先级尝试不同的支付方式
        
        类似责任链模式和工厂模式的结合
        """
        
        def __init__(self):
            self.factories = [
                (CreditCardFactory(), 10000),  # (工厂, 最大金额)
                (PayPalFactory(), 5000),
                (BankTransferFactory(), 50000)
            ]
        
        def create_best_payment(self, amount: float) -> Optional[Payment]:
            """根据金额选择最合适的支付方式"""
            for factory, max_amount in self.factories:
                if amount <= max_amount:
                    print(f"💡 选择支付方式: {factory.__class__.__name__}")
                    return factory.create_payment()
            
            print("❌ 没有合适的支付方式")
            return None
    
    chain = PaymentFactoryChain()
    
    # 测试不同金额
    amounts = [100, 3000, 8000, 60000]
    for amount in amounts:
        print(f"\n💰 处理金额: ${amount}")
        payment = chain.create_best_payment(amount)
        if payment:
            payment.pay(amount)
    
    # 2. 缓存工厂模式
    print("\n2️⃣ 缓存工厂模式")
    print("-" * 30)
    
    class CachedPaymentFactory:
        """
        缓存工厂 - 重用已创建的支付对象
        
        适合创建成本高的对象
        """
        
        def __init__(self):
            self._cache: Dict[str, Payment] = {}
            self._hit_count = 0
            self._miss_count = 0
        
        def create_payment(self, payment_type: str, **kwargs) -> Payment:
            # 生成缓存键
            cache_key = f"{payment_type}_{hash(frozenset(kwargs.items()))}"
            
            if cache_key in self._cache:
                self._hit_count += 1
                print(f"🎯 缓存命中: {cache_key}")
                return self._cache[cache_key]
            
            self._miss_count += 1
            print(f"🔍 缓存未命中，创建新对象: {cache_key}")
            
            # 创建新对象
            payment = create_payment(PaymentType(payment_type), **kwargs)
            self._cache[cache_key] = payment
            
            return payment
        
        def get_cache_stats(self) -> Dict[str, int]:
            """获取缓存统计"""
            return {
                'hits': self._hit_count,
                'misses': self._miss_count,
                'total': self._hit_count + self._miss_count,
                'hit_rate': self._hit_count / (self._hit_count + self._miss_count) if (self._hit_count + self._miss_count) > 0 else 0
            }
    
    cached_factory = CachedPaymentFactory()
    
    # 测试缓存效果
    for _ in range(3):
        payment1 = cached_factory.create_payment("credit_card", card_number="1234")
        payment2 = cached_factory.create_payment("paypal", email="test@example.com")
        payment1.pay(100)
        payment2.pay(50)
    
    stats = cached_factory.get_cache_stats()
    print(f"\n📈 缓存统计: 命中率 {stats['hit_rate']:.2%} ({stats['hits']}/{stats['total']})")


if __name__ == "__main__":
    # 运行演示
    demonstrate_factory_patterns()
    
    # 高级特性演示
    demonstrate_advanced_features()
    
    print("\n🎉 工厂方法模式演示完成！")
    print("\n📚 学习要点回顾:")
    print("1. Python提供多种灵活的工厂实现方式")
    print("2. 函数工厂比类工厂更简洁")
    print("3. 注册表模式支持动态扩展")
    print("4. 配置驱动适合企业级应用")
    print("5. Python的动态特性简化了工厂实现")